package com.bbu.javaexam.test;

import lombok.Data;

import java.util.concurrent.locks.ReentrantLock;

public class DeadLock2 {

    @Data
    static class Friend {

        private final String name;

        private final ReentrantLock lock = new ReentrantLock();

        public void request(Friend jugonger) {
            lock.lock();
            System.out.format("%s:%s 向我鞠躬%n", this.name, jugonger.getName());
            lock.unlock();
            jugonger.response(this);

        }

        public void response(Friend jugonger) {
            lock.lock();
            System.out.format("%s:%s 向我回应%n", this.name, jugonger.getName());
            lock.unlock();
        }

    }

    private final static Object lock1 = new Object();
    private final static Object lock2 = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lock1) {
                System.out.println("爸爸：你给我成绩单，我给你玩具");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (lock2) {
                    System.out.println("儿子：我给你成绩单");
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (lock2) {
                System.out.println("儿子：你给我玩具，我给你成绩单");
                synchronized (lock1) {
                    System.out.println("爸爸：我给你玩具");
                }
            }
        }).start();
    }
}
